/**
 * Copyright 2018
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.biz.controller;

import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.biz.entity.CountDto;
import io.renren.modules.biz.service.MemberService;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 主页
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
@RequestMapping("biz/index")
public class MainController {

	@Autowired
	MemberService memberService;

	@Autowired
	RedisUtils redisUtils;

	/**
	 * 首页统计
	 */
	@ResponseBody
	@RequestMapping(value = "/main")
	public R main() {
		DateTime now = DateTime.now();
		CountDto countDto = redisUtils.get("PLATFORM_MAIN_COUNT", CountDto.class);
		if (countDto == null) {
			countDto = memberService.platformStatistics(now.toString("yyyy-MM-dd"), now.plusDays(1).toString("yyyy-MM-dd"));
			redisUtils.set("PLATFORM_MAIN_COUNT", countDto, 300);
		}
		return R.ok().put("countDto", countDto).put("onlineUsers", totalOnlineUsers());
	}

	@ResponseBody
	@RequestMapping(value = "/platform")
	public R platform(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
		CountDto countDto = memberService.platformStatistics(startDate, endDate);
		return R.ok().put("countDto", countDto);
	}

	/**
	 * 在线用户
	 * 
	 * @param serverList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private int totalOnlineUsers() {
		int total = 0;
		List<String> serverList = redisUtils.get("SERVER_LIST", List.class);
		if (CollectionUtils.isNotEmpty(serverList)) {
			for (String uid : serverList) {
				String count = redisUtils.get("ONLINE_USERS_" + uid);
				if (count == null) {
					continue;
				}
				total += Integer.parseInt(count);
			}
		}
		return total;
	}
}
